#include "httprequest.h"
using std::cout;

using namespace Org;


// send a GET http request
string HttpRequest::request(char* url,
                    size_t (*pointer_to_function)(void*, size_t, size_t, void*))
{
    CURL *curl;
    CURLcode result;

    curl = curl_easy_init();

    string beans = "";

    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); // set to GET
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_ENCODING, "");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, pointer_to_function);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &beans);
        result = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }

    if (result == CURLE_OK) {}

    return beans;
}


void HttpRequest::post_multipart()
{
    CURL *curl;
    CURLcode result;

    curl = curl_easy_init();

    if(curl)
    {
        // custom headers
        struct curl_slist *headers=NULL;
        headers = curl_slist_append(headers, "Content-Type: text/xml");

        struct curl_httppost *post=NULL;
        struct curl_httppost *last=NULL;

        curl_formadd(&post, &last,
                     CURLFORM_COPYNAME, "name",
                     CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END);
        curl_formadd(&post, &last,
                     CURLFORM_COPYNAME, "project",
                     CURLFORM_COPYCONTENTS, "curl", CURLFORM_END);
        curl_formadd(&post, &last,
                     CURLFORM_COPYNAME, "xml file",
                     CURLFORM_FILECONTENT, "file.xml",
                     CURLFORM_CONTENTHEADER, headers,
                     CURLFORM_END);

        curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);

        result = curl_easy_perform(curl);
        curl_formfree(post);
    }

    if (result == CURLE_OK)
    {
        //cout << buffer << "\n";
    }
}
